<template>
  <div class="task_form_dialog">
    <el-dialog
      v-model="visible"
      :title="`${isEdit ? '编辑' : '新建'}用户`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="20vh"
      center
      width="800px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="110px"
            size="small"
          >
            <el-form-item label="登录名：" prop="username">
              <span v-if="isEdit">
                {{ form.username }}
              </span>
              <el-input
                v-else
                v-model="form.username"
                maxlength="20"
              ></el-input>
            </el-form-item>

            <el-form-item label="昵称：" prop="nickname">
              <el-input v-model="form.nickname" maxlength="20"></el-input>
            </el-form-item>

            <el-form-item v-if="!isEdit" label="密码：" prop="password">
              <el-input
                type="password"
                placeholder="密码"
                v-model="form.password"
                maxlength="18"
                show-password
              >
              </el-input>
            </el-form-item>

            <el-form-item
              v-if="!isEdit"
              label="重复密码："
              prop="repeatPassword"
            >
              <el-input
                type="password"
                placeholder="重复密码"
                v-model="form.repeatPassword"
                maxlength="18"
                show-password
              >
              </el-input>
            </el-form-item>

            <el-form-item label="姓名：" prop="truename">
              <el-input v-model="form.truename" maxlength="20"></el-input>
            </el-form-item>

            <el-form-item label="性别：" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option
                  v-for="item in genderSelectList"
                  :key="item.val"
                  :label="item.label"
                  :value="item.val"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="form.email"></el-input>
            </el-form-item>

            <el-form-item label="手机号：" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>

            <el-form-item label="个人简介：" prop="description">
              <el-input
                type="textarea"
                rows="4"
                v-model="form.description"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, nextTick, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const initFormData = () => {
  return {
    id: null,
    username: null,
    nickname: null,
    truename: null,
    gender: null,
    email: null,
    phone: null,
    description: null,
  };
};

export default {
  name: "UserFormDialog",
  props: {
    // 预加载数据
    prepareData: {
      type: Object,
      default: () => {
        return {
          taskStatusSelectList: [],
        };
      },
    },
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();

    const isEdit = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      username: [
        {
          required: !isEdit.value,
          message: "请输入登录名",
          trigger: "blur",
        },
      ],
      nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
      password: [
        {
          required: !isEdit.value,
          message: "请输入密码",
          trigger: "blur",
        },
      ],
      repeatPassword: [
        {
          required: !isEdit.value,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请重复输入密码"));
            } else if (value !== form.password) {
              callback(new Error("重复密码不一致"));
            } else {
              callback();
            }
          },
        },
      ],
    });

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (isEdit.value) {
            updateByAdmin();
          } else {
            regByAdmin();
          }
        } else {
          return false;
        }
      });
    };

    // 管理员修改用户
    const updateByAdmin = () => {
      confirmBtnLoading.value = true;
      $api.users
        .updateByAdmin(form)
        .then((res) => {
          confirmBtnLoading.value = false;
          ElMessage.success("操作成功！");
          // 触发事件，把数据传递给父组件
          context.emit("refresh");
          close();
        })
        .catch((err) => {
          confirmBtnLoading.value = false;
          console.error("updateByAdmin error: ", err);
        });
    };

    // 管理员注册新用户
    const regByAdmin = () => {
      confirmBtnLoading.value = true;
      $api.users
        .regByAdmin(form)
        .then((res) => {
          confirmBtnLoading.value = false;
          ElMessage.success("操作成功！");
          // 触发事件，把数据传递给父组件
          context.emit("refresh");
          close();
        })
        .catch((err) => {
          confirmBtnLoading.value = false;
          console.error("regByAdmin error: ", err);
        });
    };

    // 打开弹框
    const open = (row) => {
      if (row) {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
        // if (!props.prepareData.taskStatusSelectList) {
        //   return ElMessage.warning("关键数据未获取到，请关闭重新打开页面");
        // }
      }
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    const genderSelectList = reactive([
      { label: "男", val: "1" },
      { label: "女", val: "0" },
    ]);

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      form,
      rules,
      open,
      close,
      handleConfirm,
      isEdit,
      genderSelectList,
    };
  },
};
</script>
